Skip to content

ENH: Replace the shell wheel build system with Python (supersedes #302) - #309

Closed
hjmjohnson wants to merge 241 commits into
InsightSoftwareConsortium:mainfrom
BRAINSia:itk6-build-system-v2
Closed

hjmjohnson wants to merge 241 commits into
InsightSoftwareConsortium:mainfrom
BRAINSia:itk6-build-system-v2

Conversation

@hjmjohnson

@hjmjohnson hjmjohnson commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Replaces the shell and PowerShell wheel-build system with a pixi-driven
Python one, and moves ITK 6 to stable-ABI (abi3) wheels on
manylinux_2_28, macOS arm64 14.0, and Windows x86_64. Supersedes #302.

Linux and macOS wheels now build with --dead-strip by default (port of
SimpleITK/SimpleITK#2784): itk_core shrinks from 89.5 to 71.4 MB on Linux
and from 61.5 to 49.3 MB on macOS, with unchanged outputs.

Successfully built on Windows, macOS arm64, Linux x86_64, and Linux
aarch64. The Doxygen/environment defect found by @dzenanz is fixed: build
tools now resolve inside the target --platform-env, and launching from
the wrong environment fails immediately with the environment name to use.

Build caches for all four platforms are published to ITKPythonBuilds
v6.0rc01.dev20260915; the macOS cache targets macOS 14.0. Those caches
and the platform builds below predate the eighth package,
itk-filtering-extra; the current tree has been built only on Linux
x86_64 (all 8 packages, see the --dead-strip measurements).

Release decisions for reviewers: a new PyPI package, itk-filtering-extra
(the filtering modules ingested from remote modules), and itk-io now
requires itk-numerics.

Platform verification — clean builds from this branch

Every row is a from-scratch build of this branch, not an incremental one,
made before itk-filtering-extra was added (hence 7 wheels).

Platform Result Time Wheels
Linux x86_64 pass — 7 × cp311-abi3-manylinux_2_28_x86_64
Linux aarch64 pass on retry 39 min 7 × cp311-abi3-manylinux_2_28_aarch64
macOS arm64 pass 93 min 7 × cp311-abi3-macosx_14_0_arm64
Windows x86_64 pass — 7 × cp311-abi3-win_amd64

macOS binaries were checked with otool -l: real .so files report
minos 14.0, matching their macosx_14_0_arm64 tag. That check matters
because a component wheel tagged below its true minos installs on older
macOS and then fails in dyld at import — installable and broken, rather
than loudly uninstallable.

Remote-module end-to-end (the consumer path)

Proven on Windows x86_64 and Linux x86_64, each run as a fresh
consumer with zero ITK wheels present beforehand, so a leftover
artifact could not produce a false pass.

Linux x86_64, ITKBioCell, 8 minutes, rc=0:

  • itk_biocell-1.0.0-cp311-abi3-manylinux_2_28_x86_64.whl, 0.58 MB
  • Requires-Dist: itk<7,>=6.0.0b1 — the dependency rewrite fired
  • 2 bundled libraries — genuinely repaired by auditwheel
  • pyproject.toml restored byte-identical after the build

An earlier Windows pass was found to be riding on leftover wheels; the
zero-wheel precondition was added in response and both platforms were
re-run under it.

--dead-strip: measurements

Linux links with -ffunction-sections -fdata-sections, --gc-sections,
and a version script that exports only PyInit_* from each Python module.
--no-dead-strip opts out. User -D flags such as
-DCMAKE_CXX_FLAGS:STRING=... are merged with these, not replaced.

Measure Before --dead-strip
_ITKCommonPython exported symbols 33,625 84
itk_core wheel, Linux x86_64 89.5 MB 71.4 MB
ITK Python tests (252) 244 pass 244 pass, same 8 failures
Registration benchmark outputs (17 cases) bit-identical

The export limit carries the saving; --gc-sections alone gave 3-5%.
Linux figures are from the pushed configuration (default linker, with a
user -DCMAKE_CXX_FLAGS:STRING=-pipe merged in). Linking with gold gave
wheels about 1% smaller (itk_core 70.7 MB) and was dropped. A remote
module (ITKSimpleITKFilters) built against the stripped wheels gives
identical output in all four old/new ITK and module combinations.

Windows needs no change: a .pyd already exports only PyInit_* (84 on
_ITKCommonPython), and Release links use /OPT:REF,ICF by default.
macOS Python modules link with -dead_strip and export only _PyInit_*:
wheels are 20-48% smaller (itk_core 61.5 to 49.3 MB), benchmark outputs
are identical, and BSpline LBFGSB registration runs 15% faster.
-dead_strip alone changed nothing (<0.1%).

The 8 ITK test failures occur with and without the change and come from
the wheel configuration (unwrapped return types such as
SinusoidSpatialFunctionF4PD4, TransformToStrainFilter for
Transform[D,3,3], itk.Ransac) or missing test data
(Real-DSA-01-Speed-02.mhd).

Unit tests and hooks
  • pytest: 205 passed. pytest is a developer-only dependency; the
    normal build path does not import it.
  • pre-commit run --all-files: exit 0, every hook Passed
    (black, ruff, shellcheck, shfmt, taplo, yaml/toml, whitespace).
Known caveat: intermittent aarch64 link truncation

One clean aarch64 build failed while linking:

FAILED: lib/libITKIOStimulate-6.0.a
ranlib: error reading itkStimulateImageIO.cxx.o: file truncated

The identical clean build then passed, with no truncation and no short
object files. Evidence points at the container file-sharing layer rather
than this branch: 158 GB free at the time, the truncated archive was
exactly 49,152 bytes (12 × 4096, a dropped write tail rather than a
partial compile), and aarch64 is the only platform writing through a
Docker bind mount onto a macOS filesystem.

Docker Desktop updated itself between the two runs (29.7.2 → 29.8.0), so
the version cannot be credited with the fix, and one pass does not
disprove an intermittent fault. Recommended handling: retry a clean
build first; do not treat a truncation as a defect in this branch.

Commit series

Topical commits, no fixups and no merge commits, now including
@dzenanz's wheels-6.0b3 series and the --dead-strip commits. Some
BUG: commits fix earlier commits in this series; they are kept separate
because they record distinct defects found in testing.

Beyond the build-system replacement, the series also adds:

  • release-wheels, one command per release build machine
  • the ITK modules ingested from remote modules, built into the wheels
  • itk-filtering-extra, a new package for the ingested filtering modules
  • itk-io depending on itk-numerics
  • a build failure when a wheel exceeds the 100 MB PyPI limit
  • building a remote module against an installed ITK (--module-itk-dir install)
  • ninja jobs bounded by physical memory (ITK_BUILD_JOBS overrides)

Cavan Riley is credited via Co-Authored-By on the seven commits
carrying his original work.

@dzenanz dzenanz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have taken a look. There is too much code to look carefully. I tried running locally:

M:\a\IPP>pixi run python3 "C:\Misc\ITKPythonPackage\scripts\build_wheels.py" --platform-env windows-py311 --itk-source-dir C:/Dev/ITK-git
Error:   × could not find pixi.toml or pyproject.toml with tool.pixi at directory M:\a\IPP


M:\a\IPP>cd C:\Misc\ITKPythonPackage

M:\a\IPP>c:

C:\Misc\ITKPythonPackage>pixi run python3 "C:\Misc\ITKPythonPackage\scripts\build_wheels.py" --platform-env windows-py311 --itk-source-dir C:/Dev/ITK-git
 WARN Encountered 2 warnings while parsing the manifest:
  ⚠ the `[system-requirements]` table is deprecated in favor of virtual packages on `platforms`
    ╭─[C:\Misc\ITKPythonPackage\pixi.toml:82:1]
 81 │
 82 │ ╭─▶ [feature.manylinux228-build.system-requirements]
 83 │ │   linux = "5.4"
 84 │ ├─▶ libc = { family = "glibc", version = "2.28" }
    · ╰──── declare these on the `platforms` entries instead
 85 │
    ╰────
  help: e.g. platforms = [{ platform = "linux-64", cuda = "12" }]

  ⚠ the `[system-requirements]` table is deprecated in favor of virtual packages on `platforms`
    ╭─[C:\Misc\ITKPythonPackage\pixi.toml:95:23]
 94 │ platforms = ["osx-arm64"]
 95 │ system-requirements = { macos = "14.0" }
    ·                       ─────────┬────────
    ·                                ╰── declare these on the `platforms` entries instead
 96 │
    ╰────
  help: e.g. platforms = [{ platform = "linux-64", cuda = "12" }]

Error launching 'python3': The system cannot find the path specified. (os error 3)

C:\Misc\ITKPythonPackage>pixi run python "C:\Misc\ITKPythonPackage\scripts\build_wheels.py" --platform-env windows-py311 --itk-source-dir C:/Dev/ITK-git
 WARN Encountered 2 warnings while parsing the manifest:
  ⚠ the `[system-requirements]` table is deprecated in favor of virtual packages on `platforms`
    ╭─[C:\Misc\ITKPythonPackage\pixi.toml:82:1]
 81 │
 82 │ ╭─▶ [feature.manylinux228-build.system-requirements]
 83 │ │   linux = "5.4"
 84 │ ├─▶ libc = { family = "glibc", version = "2.28" }
    · ╰──── declare these on the `platforms` entries instead
 85 │
    ╰────
  help: e.g. platforms = [{ platform = "linux-64", cuda = "12" }]

  ⚠ the `[system-requirements]` table is deprecated in favor of virtual packages on `platforms`
    ╭─[C:\Misc\ITKPythonPackage\pixi.toml:95:23]
 94 │ platforms = ["osx-arm64"]
 95 │ system-requirements = { macos = "14.0" }
    ·                       ─────────┬────────
    ·                                ╰── declare these on the `platforms` entries instead
 96 │
    ╰────
  help: e.g. platforms = [{ platform = "linux-64", cuda = "12" }]

Running >>>>>: git fetch --tags origin  ; # in cwd=C:\Dev\ITK-git with check=False

Traceback (most recent call last):
  File "C:\Misc\ITKPythonPackage\scripts\build_wheels.py", line 628, in <module>
    build_wheels_main()
    ~~~~~~~~~~~~~~~~~^^
  File "C:\Misc\ITKPythonPackage\scripts\build_wheels.py", line 450, in build_wheels_main
    raise RuntimeError(
    ...<2 lines>...
    )
RuntimeError: Failed to fetch ITK tags in C:\Dev\ITK-git: fatal: 'origin' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.


C:\Misc\ITKPythonPackage>

@dzenanz

dzenanz commented Sep 18, 2026

Copy link
Copy Markdown
Member

This seems to be doing something: C:\Misc\ITKPythonPackage>pixi run python scripts/build_wheels.py --platform-env windows-py311 --itk-git-tag v6.0b01

@dzenanz

dzenanz commented Sep 18, 2026

Copy link
Copy Markdown
Member

That failed too: run.log

@hjmjohnson
hjmjohnson force-pushed the itk6-build-system-v2 branch 8 times, most recently from ef0c2d4 to 1af2b15 Compare September 19, 2026 20:08
@hjmjohnson

Copy link
Copy Markdown
Member Author

Windows verification complete — handing back to Linux/macOS

Everything Windows-specific on this branch is now verified by real builds, and one cross-platform defect found along the way is fixed. Head is 1af2b15 (10 commits, no BUG: commits — every fix is folded into the commit that introduced the code). Coordination detail lives in the shared gist; this is the summary a reviewer needs.

What was verified on Windows 11 / VS 2022 (i7-9800X, 32 GB)

step result
clean cache build from ef0c2d4 (pixi reinstalled, everything deleted first) 7 × cp311-abi3-win_amd64, cache 226,973,373 B, published to v6.0rc01.dev20260915, byte-identical
DLL bundling 9 DLLs in itk_core incl. itk_core.libs/tbb12.dll; wheels import in a clean venv with PATH stripped to System32 and ITK_EAGER_IMPORT=1
remote module (ITKBioCell) via the documented script, as a fresh consumer step 06 reached; Requires-Dist: itk<7,>=6.0.0b1; repaired wheel (with msvcp140.dll) in the module's own dist/; pyproject.toml restored byte-identical
unit tests 97 passed on Windows (was 11 failed / 81 passed)

Defects fixed on this branch by the Windows work

All Windows-only unless noted; none were reachable from Linux/macOS testing.

  1. TargetPlatform.detect() read PROCESSOR_ARCHITECTURE from the config mapping, not the environment — Unknown machine '' on any Windows build (POSIX hidden by os.uname).
  2. Nested pixi run from inside an activated env overflowed the cmd.exe 8191-char limit (The input line is too long) — in the interpreter probe and in echo_check_call.
  3. build_tarball() deleted the seven freshly built wheels from dist/ and reported rc=0.
  4. pixi's vs2022 activation exports CMAKE_GENERATOR="Visual Studio 17 2022"; scikit-build-core honoured it, and the multi-config generator broke ITK wrapping's file(GENERATE) (castxml.inc "written multiple times"). Module wheels now pass -GNinja.
  5. Cross-platform: the dependency rewrite emitted itk >= 6.0, < 7, which PEP 440 makes unsatisfiable by any 6.0.0bN (6.0.0b2 < 6.0); --pre cannot rescue it. Now >= 6.0.0b1, < 7.
  6. delvewheel --add-path pointed at a non-existent oneTBB directory.
  7. pixi global install aria2 always fails on win-64 and printed a red error that looked fatal.
  8. A failed git checkout <tag> forced git checkout main, moving a cache-restored ITK source off the commit its binaries were built from.
  9. 7-Zip -r treated build as a recursive pattern and swept a remote module's CMake tree into the cache; consumers then hit generator ... does not match.
  10. Windows fixup_wheel ignored remote_module_wheel and wrote the repaired module wheel to the main dist/, leaving the unrepaired one as the module's only artifact.
  11. Cross-platform (gist T7): on the --skip-itk-wheel-build path, 04_post_build_fixup and 05_final_import_test still ran against ITK wheels that were never built, and step 05 aborted the run before the module wheel. Both are now registered as _skipped no-ops when 03 is skipped; the step table was extracted into build_step_table() and is covered by tests. The earlier Windows "pass" of step 05 was an artifact of leftover wheels on the build machine — verified by reproducing the failure with dist/ empty, then re-running after the fix.

Plus three test fixes so the suite runs on Windows (os.uname monkeypatching, a cross-build test that inferred the host OS, a symlink that needs SeCreateSymbolicLinkPrivilege), and install-pixi.ps1 added to .gitignore.

For Linux/macOS

  • T2 (Linux remote-module test) is unblocked by fix 11 — git fetch, rebuild from 1af2b15 or later. Expected Requires-Dist is itk<7,>=6.0.0b1, not the older >= 6.0, < 7.
  • The published caches were built from ef0c2d4 and carry the pre-fix-11 scripts. The documented module scripts re-clone the branch when ITKPYTHONPACKAGE_TAG is set, so consumers get the fix; a consumer without that variable does not. Rebuilding caches is not urgent but is why cache and branch can disagree.
  • Not on this branch: an experiment bounding ninja jobs by physical memory (-j = min(cpu, ram/4) with a link pool). Motivated by two OOM kills at -j16 on 32 GB; peak memory dropped to 9.9 GB, but the timing run was confounded and is parked on a separate local branch. Worth revisiting for CI runner sizing.

@hjmjohnson
hjmjohnson force-pushed the itk6-build-system-v2 branch 2 times, most recently from c219d94 to afdfaf8 Compare September 20, 2026 13:19
@hjmjohnson

Copy link
Copy Markdown
Member Author

Thanks for running it locally — your run.log found a real defect in this
branch, and your two earlier comments are now answered by the Windows
verification. Rebased onto current main and pushed; head is afdfaf8.

Your build failure is our bug, not your invocation. The log ends at:

CMake Error: Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
  -DITK_WRAP_DOC:BOOL='ON'  -DDOXYGEN_EXECUTABLE:FILEPATH='C:\Dev\doxygen'

ITK_WRAP_DOC=ON is set unconditionally and DOXYGEN_EXECUTABLE comes from
which_required("doxygen"), which aborts when it cannot resolve. But
doxygen is not declared in pixi.toml, so it is an undeclared external
prerequisite. My Windows runs passed only because that machine happens to have
a working Doxygen. That defeats the point of using pixi for a hermetic
toolchain, and it is being fixed before this leaves draft.

310-x64 is removed (your inline comment). It was a leftover, and it could
never have resolved: the only environments in pixi.toml are dev, publish,
linux-py311, manylinux228-py311, macosx-py311, and windows-py311.
ITK 5.4 is out of scope for this build system.

This PR stays WIP until the Doxygen prerequisite is resolved. "Too much
code to look carefully" is fair — please don't spend review time on the whole
diff yet; I'll ping you when it is ready for a real pass.

Platform verification status as of afdfaf8
Platform Clean build Remote-module end-to-end
Linux x86_64 pass pass (ITKBioCell, 8 min)
Linux aarch64 pass on retry —
macOS arm64 pass (93 min) —
Windows x86_64 pass pass

97 unit tests pass; pre-commit run --all-files exits 0.

One known caveat: a single aarch64 clean build failed while linking with a
truncated object file, and the identical rebuild passed. Evidence points at the
Docker bind-mount layer rather than this branch (the truncated archive was
exactly 49,152 bytes, a dropped write tail, and aarch64 is the only platform
writing through a bind mount onto a macOS filesystem). Docker updated itself
between the two runs, so the version cannot be credited with the fix.

@hjmjohnson hjmjohnson changed the title ENH: Replace the shell wheel build system with Python (supersedes #302) WIP: ENH: Replace the shell wheel build system with Python (supersedes #302) Sep 20, 2026
@hjmjohnson

Copy link
Copy Markdown
Member Author

@dzenanz thank you for the log file — it identified a real bug, and that bug is
now fixed in e53db8d.

This should have been a WIP: PR from the start, and that is my fault. It
was opened primarily to get the code onto my Windows machine for testing and to
track the outstanding testing tasks, not to request review. It is now retitled
WIP:. There are still refinements to make, but I have successfully run it on
Windows, macOS arm64, Linux x86_64, and Linux aarch64 builds.

What your log found, and the fix

Your run failed at:

CMake Error: Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
  -DDOXYGEN_EXECUTABLE:FILEPATH='C:\Dev\doxygen'

doxygen is declared in pixi.toml and is present in every build
environment. The bug was that your command used pixi run without -e,
which lands in the default environment. The script then resolved its build
tools from whatever was on the system PATH rather than from the target
environment, and handed CMake a C:\Dev\doxygen that is not a Doxygen
executable. Reproduced here — in default, cmake, ninja, doxygen, and
git all resolve to system paths.

Two changes:

  1. cmake, ninja, doxygen, and git now resolve inside the target
    --platform-env
    , the same way the Python interpreter already did. A stray
    same-named executable on PATH can no longer reach CMake.
  2. Running outside the requested environment now fails immediately, before
    any work, naming the environment you want:
==============================================================
  WRONG ENVIRONMENT - build aborted before doing any work
==============================================================
  running in : the 'default' pixi environment
  required   : 'windows-py311'

  Re-run with the environment selected:
      pixi run -e windows-py311 python scripts/build_wheels.py ...

  'pixi run' without '-e' uses the 'default' environment, which
  does NOT carry the pinned cmake, ninja, doxygen and git. The
  build would silently pick up whatever is on the system PATH.
==============================================================

Six regression tests cover both (103 total, up from 97). Your exact command
shape now exits 1 with that message instead of failing minutes later inside
CMake.

@hjmjohnson
hjmjohnson force-pushed the itk6-build-system-v2 branch 2 times, most recently from fb3e45b to 42922e0 Compare September 20, 2026 14:10
@hjmjohnson
hjmjohnson force-pushed the itk6-build-system-v2 branch 3 times, most recently from 1af2b15 to ca9994a Compare September 20, 2026 14:22
A frozen dataclass holding the settings build_wheels.py collects in
package_env_config, with precise types (Path, bool, OS, Arch, and
None for settings a platform does not have). from_args_and_env()
converts and validates the parsed arguments, the environment, and the
resolved tools in one place, raising BuildConfigError that names the
field and its value. to_environment() renders the settings as the
environment variables the build tools receive, in the same keys,
spellings, order, and omissions.

Nothing uses it yet.
configure_one_pyproject_file and its helpers read only the ITK source
directory, git tag, and package version from the whole build
configuration. A frozen PyprojectInputs carries those three, so the
module no longer takes a Mapping[str, Any]. The command line builds it
from the env file and names every missing setting at once, where it
stopped at the first with a bare KeyError.

The generated pyproject.toml files are unchanged.
build_wheels.py now builds a BuildConfig and hands it to the builders,
which read typed attributes in place of package_env_config lookups.
The builders no longer write into the configuration: the ITKPythonPackage
directories come from ipp_dir, the build type is the BUILD_TYPE
constant, and the oneTBB location is the builder's tbb_dir.
subprocess_environment() gives auditwheel the same variables as before,
config.to_environment() followed by the builder's five keys.

Input the build accepted until now and refuses at startup, naming the
setting and its value:

- a macOS deployment target that is not a version such as 14.0 (it
  produced a malformed CMAKE_OSX_DEPLOYMENT_TARGET and wheel tag);
- an empty Python interpreter path from the pixi probe;
- an empty ITK git tag or ITK package version.

The CC and CXX lookups are removed; nothing put either key in the
configuration. CMake, python -m build, and repair commands, their
environments, the step table, and the build-input fingerprint settings
are identical on every platform.
BuildReport and StepRecord dataclasses replace the dict[str, Any]
report in build_manager.py. to_json() writes the same keys as before
plus "version": 1; from_json() reads a report without a version field
as version 1, so build trees from earlier runs are reused as they were.
tests/data/build_log_unversioned.json is a report written by the
previous BuildManager.

A report the build used to accept and now refuses, naming the field
(the build stops with "Fix or delete it to continue", as for corrupt
JSON):

- one missing created_at, updated_at, or steps, or a step without a
  status (an empty "{}" report was read as having no steps);
- a step status other than pending, running, done, or failed;
- a non-string timestamp, error, or input value, or a non-numeric
  duration;
- a version other than 1;
- a malformed steps section in a report whose inputs changed, which
  was ignored because every step reran.
@hjmjohnson

Copy link
Copy Markdown
Member Author

Superseded by #312. Its content is byte-identical to this PR's head (same tree hash), organized as 21 commits for easier review: the Scientific Python rules first, then one commit per feature.

@hjmjohnson hjmjohnson closed this Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants